package com.lanou3g.musicenjoy.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.lanou3g.musicenjoy.R;
import com.lanou3g.musicenjoy.download.DownloadTask;
import com.lanou3g.musicenjoy.download.DownloadUtil;
import com.lanou3g.musicenjoy.download.NotificationBean;

public class DownloadServices extends Service {
    private Context mContext = DownloadServices.this;
    /**
     * 正在下载
     */
    private final int DOWN_LOADING = 0;
    /**
     * 下载完成
     */
    private final int DOWN_COMPLETE = 1;
    /**
     * 下载失败
     */
    private final int DOWN_ERR = 2;
    /**
     * Timer 执行时间间隔
     */
    private final int TIMER_PERIOD = 1500;

    protected Timer mTimer;
    //消息通知栏
    protected NotificationManager mNotificationManager;
    private Bitmap bitmap = null;
    private Handler mHandler;
    private boolean isFlag = false;
    /**
     * 下载任务管理
     */
    protected Map<String, DownloadTask> map_downloadtask;

    //绑定服务
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    //销毁服务
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        mTimer = new Timer();
        //调取系统服务
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        map_downloadtask = new HashMap<String, DownloadTask>();
    }

    @Override
    public int onStartCommand(Intent intent, final int flags, int startId) {
        String mUrl = intent.getExtras().getString("url");
        int mNotifyId = intent.getExtras().getInt("notifyId");
        final String picUrl = intent.getExtras().getString("picUrl");
        String title = intent.getExtras().getString("title");
        Notification mNotification;
//        DownlaodSync sync = new DownlaodSync();
//        sync.execute(picUrl);

//        mHandler = new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                bitmap = (Bitmap) msg.obj;
//
//            }
//        };
//        mHandler = new Handler(new Handler.Callback() {
//            @Override
//            public boolean handleMessage(Message msg) {
//                bitmap = (Bitmap) msg.obj;
//                return false;
//            }
//        });

//        synchronized (bitmap) {
//            mNotification = new NotificationBean(this, R.mipmap.music, "开始下载", System.currentTimeMillis(),
//                    bitmap, title);
//        }

        mNotification = new NotificationBean(this, R.mipmap.music, "开始下载", System.currentTimeMillis(),
                    picUrl, title);
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    URL url = new URL(picUrl);
//                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//                    if (connection.getResponseCode() == 200) {
//                        InputStream is = connection.getInputStream();
//                        bitmap = BitmapFactory.decodeStream(is);
//                        is.close();
//                        connection.disconnect();
//
//                    }
//                } catch (MalformedURLException e) {
//                    e.printStackTrace();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        };
//
//        Thread mThread = new Thread(runnable);
//        mThread.start();
//
//        try {
//            mThread.join();//当子线程执行完成之后再执行主线程
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }

        Log.i("nnnn", bitmap + "");


        System.out.println("NotifyId = " + mNotifyId);

        if (map_downloadtask.containsKey(mUrl)) {
            Toast.makeText(mContext, "已存在此下载任务", Toast.LENGTH_SHORT).show();
        } else {
            DownloadTask mDownloadTask = new DownloadTask();
            mDownloadTask.setUrl(mUrl);
            mDownloadTask.setNotifyID(mNotifyId);
            mDownloadTask.setNotification(mNotification);
            map_downloadtask.put(mUrl, mDownloadTask);
            //重启线程
            Runnable mRunnable = new MyRunnable(mDownloadTask, title);
            //开启新线程
            new Thread(mRunnable).start();
        }

        return super.onStartCommand(intent, flags, startId);
    }


    class MyRunnable implements Runnable {
        private DownloadUtil mDownUtil = new DownloadUtil();
        private DownloadTask mDownTask;
        private Handler mHandler;
        private TimerTask mTimerTask;
        private String name;

        public MyRunnable(DownloadTask downTask, String name) {
            super();
            this.mDownTask = downTask;
            this.mHandler = new MyHandler(mDownUtil);
            this.name = name;
            this.mTimerTask = new MyTimerTask(mDownUtil, mHandler, mDownTask);
        }

        @Override
        public void run() {
            mTimer.schedule(mTimerTask, 0, TIMER_PERIOD);
            mDownUtil.downloadFile(mDownTask.getUrl(), name);
        }

    }



    class MyTimerTask extends TimerTask {
        private Handler mHandler;
        private DownloadUtil mDownUtil;
        private DownloadTask mDownTask;
        private DownloadUtil.IOnDownloadListener mListener;

        public MyTimerTask(DownloadUtil downUtil, Handler handler, DownloadTask downTask) {
            super();
            this.mHandler = handler;
            this.mDownUtil = downUtil;
            this.mDownTask = downTask;
            this.mListener = new DownloadUtil.IOnDownloadListener() {
                @Override
                public void updateNotification(int progress, int totalSize, File downFile) {
                    // TODO Auto-generated method stub
                    int rate = 0;
                    // 计算百分比
                    if (totalSize > 0) {
                        rate = progress * 100 / totalSize;
                        //下载进行中
                        mHandler.obtainMessage(DOWN_LOADING, rate, mDownTask.getNotifyID(), mDownTask.getNotification()).sendToTarget();
                    } else if (totalSize == 0) {

                        //下载进行中
                        mHandler.obtainMessage(DOWN_LOADING, 0, mDownTask.getNotifyID(), mDownTask.getNotification()).sendToTarget();
                    } else {
                        cancel();

                        //下载失败
                        mHandler.obtainMessage(DOWN_ERR, mDownTask).sendToTarget();
                    }
                    // 是否下载结束
                    if (totalSize > 0 && null != downFile && totalSize == (int) downFile.length()) {
                        cancel();
                        //下载完成
                        mHandler.obtainMessage(DOWN_COMPLETE, 0 , mDownTask.getNotifyID(), downFile).sendToTarget();
                        map_downloadtask.remove(mDownTask.getUrl());// 移除已完成任务
                        System.out.println("DOWN_COMPLETE ==> totalSize ==> " + totalSize);
                    }
                }

            };
        }

        @Override
        public void run() {
            mDownUtil.setOnDownloadListener(mListener);
        }
    }


    class MyHandler extends Handler {
        private DownloadUtil mDownUtil;

        public MyHandler(DownloadUtil downUtil) {
            super();
            this.mDownUtil = downUtil;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case DOWN_LOADING://下载过程中
                    ((Notification) msg.obj).contentView.setProgressBar(R.id.pb, 100, msg.arg1, false);
                    ((Notification) msg.obj).contentView.setTextViewText(R.id.tv, "下载" + msg.arg1 + "%");
                    mNotificationManager.notify(msg.arg2, ((Notification) msg.obj));
                    System.out.println("DOWN_LOADING --> mNotifyId --> " + msg.arg2 + " --> " + msg.arg1 + "%");
                    break;
                case DOWN_COMPLETE://下载完成
                    mNotificationManager.cancel(msg.arg2);
                    removeMessages(DOWN_LOADING);
                    Toast.makeText(mContext, "下载完成", Toast.LENGTH_SHORT).show();
                    //	mDownUtil.installApk(mContext, (File)msg.obj);
                    System.out.println("======================DOWN_COMPLETE================================");
                    stopService();
                    break;
                case DOWN_ERR://下载失败
                    removeMessages(DOWN_LOADING);
                    map_downloadtask.remove(((DownloadTask) msg.obj).getUrl());
                    Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
                    stopService();
                    break;
                default:
                    break;
            }
        }

        /**
         * 如果无下载任务，关闭服务
         */
        private void stopService() {
            if (map_downloadtask.isEmpty()) {
                stopSelf(-1);

            }
        }


    }

//    class DownlaodSync extends AsyncTask<String, Integer, Bitmap> {
//
//        private Bitmap bitmap;
//        @Override
//        protected Bitmap doInBackground(String... params) {
//            String path = params[0];
//            try {
//                URL url = new URL(path);
//                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//                if (connection.getResponseCode() == 200) {
//                    InputStream is = connection.getInputStream();
//                    bitmap = BitmapFactory.decodeStream(is);
//                    is.close();
//                    connection.disconnect();
//                }
//            } catch (MalformedURLException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            return bitmap;
//        }
//
//        @Override
//        protected void onPostExecute(Bitmap bitmap) {
//            super.onPostExecute(bitmap);
//
//            //mHandler.obtainMessage(0, bitmap).sendToTarget();
//            Message message = Message.obtain();
//            Log.i("nnnn", bitmap + "220");
//            message.obj = bitmap;
//            mHandler.sendMessage(message);
//        }
//    }

}
